<template>
  <el-drawer :model-value="visible" size="720px" :with-header="true" @close="onClose">
    <template #header>
      <div class="drawer-header">
        <span class="node-icon" v-if="nodeIconUnicode" :style="{ color: nodeIconColor }">{{ nodeIconUnicode }}</span>
        <span class="title">LLM</span>
      </div>
    </template>

    <div class="drawer-body">
      <el-form :model="form" label-position="left" class="name-form">
        <el-form-item label="名称">
          <el-input v-model="form.name" maxlength="10" placeholder="请输入名称（最多10字）" />
        </el-form-item>
      </el-form>

      <div class="section">
        <div class="section-header">
          <span>模型</span>
        </div>
        <el-select v-model="form.model" placeholder="选择模型" class="model-select" @change="emitSave">
          <el-option v-for="m in modelOptions" :key="m.value" :label="m.label" :value="m.value" />
        </el-select>
      </div>

      <div class="section">
        <div class="section-header">
          <span>上文</span>
          <el-button type="primary" link @click="addContext">设置变量值</el-button>
        </div>
        <div class="kv-list">
          <div class="kv-row kv-row--context" v-for="(c, i) in form.context" :key="i">
            <el-input v-model="c.name" placeholder="变量名" @input="emitSave" />
            <el-input v-model="c.value" placeholder="变量值或 {{var}}" @input="emitSave" />
            <el-button circle size="small" type="danger" class="del-btn" @click="removeContext(i)"><el-icon><Close /></el-icon></el-button>
          </div>
        </div>
      </div>

      <div class="section">
        <div class="section-header">
          <span>SYSTEM</span>
        </div>
        <div class="msg-list">
          <div class="msg-item" v-for="(m, i) in systemMessages" :key="`sys-${i}`">
            <el-input v-model="m.content" type="textarea" :autosize="{ minRows: 6, maxRows: 12 }" placeholder="系统提示" @input="emitSave" @change="emitSave" />
          </div>
        </div>
      </div>

      <div class="section">
        <div class="section-header">
          <span>USER</span>
          <el-button type="primary" link @click="addMessage('user')">新增</el-button>
        </div>
        <div class="msg-list">
          <div class="msg-item" v-for="(m, i) in userMessages" :key="`usr-${i}`">
            <div class="msg-actions" v-if="i > 0">
              <el-button circle size="small" type="danger" class="del-btn" @click="removeUserMessage(i)"><el-icon><Close /></el-icon></el-button>
            </div>
            <el-input v-model="m.content" type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" placeholder="用户消息" @input="emitSave" @change="emitSave" />
          </div>
        </div>
      </div>

      <div class="section">
        <div class="section-header">
          <span>高级设置</span>
        </div>
        <div class="adv-grid">
          <div class="adv-item">
            <span class="adv-label">温度</span>
            <el-slider v-model="form.temperature" :min="0" :max="2" :step="0.1" @change="emitSave" />
          </div>
          <div class="adv-item">
            <span class="adv-label">视图</span>
            <el-switch v-model="form.vision" @change="emitSave" />
          </div>
          <div class="adv-item">
            <span class="adv-label">失败重试</span>
            <el-input-number v-model="form.retry" :min="0" :max="5" @change="emitSave" />
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { defineComponent, reactive, computed, watch } from 'vue'
import { Close } from '@element-plus/icons-vue'
import { componentRegistry } from '@/components/WorkFlow/core/ComponentRegistry'

export default defineComponent({
  name: 'LLMDrawer',
  components: { Close },
  props: {
    visible: { type: Boolean, default: false },
    nodeData: { type: Object, default: null }
  },
  emits: ['save', 'close'],
  setup(props, { emit }) {
    const form = reactive({
      name: '',
      model: '',
      context: [],
      messages: [],
      temperature: 0.7,
      vision: false,
      retry: 0
    })

    const modelOptions = [
      { label: 'deepseek-chat', value: 'deepseek-chat' },
      { label: 'gpt-4o-mini', value: 'gpt-4o-mini' },
      { label: 'glm-4', value: 'glm-4' },
      { label: 'qwen-plus', value: 'qwen-plus' }
    ]


    /**
     * 初始化表单数据
     * @returns {void}
     */
    const initForm = () => {
      const d = props.nodeData || {}
      const llm = d.llm || {}
      form.name = (d.name || '').toString().slice(0, 10)
      form.model = llm.model || 'deepseek-chat'
      form.context = Array.isArray(llm.context) ? llm.context.map(x => ({ ...x })) : []
      form.messages = Array.isArray(llm.messages) ? llm.messages.map(x => ({ ...x })) : defaultMessages()
      form.temperature = typeof llm.temperature === 'number' ? llm.temperature : 0.7
      form.vision = !!llm.vision
      form.retry = typeof llm.retry === 'number' ? llm.retry : 0
    }

    /**
     * 默认消息集合
     * @returns {Array}
     */
    const defaultMessages = () => [
      { role: 'system', content: '' },
      { role: 'user', content: '' }
    ]

    /**
     * 规范化系统提示词为单个
     * @returns {void}
     */
    const normalizeSystem = () => {
      let first = -1
      for (let i = 0; i < form.messages.length; i++) {
        if (form.messages[i].role === 'system') {
          if (first === -1) first = i
          else {
            form.messages.splice(i, 1)
            i--
          }
        }
      }
      if (first === -1) form.messages.unshift({ role: 'system', content: '' })
    }

    /**
     * 保证至少存在一个用户消息（默认只有一个）
     * @returns {void}
     */
    const ensureMinUserMessage = () => {
      const hasUser = form.messages.some(m => m.role === 'user')
      if (!hasUser) {
        form.messages.push({ role: 'user', content: '' })
      }
    }

    /**
     * 实时保存
     * @returns {void}
     */
    const emitSave = () => {
      const llmData = JSON.parse(JSON.stringify({
        model: form.model,
        context: form.context,
        messages: form.messages,
        temperature: form.temperature,
        vision: form.vision,
        retry: form.retry
      }))
      emit('save', {
        name: (form.name || '').toString().slice(0, 10),
        llm: llmData
      })
    }

    /**
     * 新增上文变量
     * @returns {void}
     */
    const addContext = () => { form.context.push({ name: '', value: '' }); emitSave() }

    /**
     * 删除上文变量
     * @param {number} i 索引
     * @returns {void}
     */
    const removeContext = (i) => { form.context.splice(i, 1); emitSave() }

    /**
     * 新增消息
     * @param {string} role 角色
     * @returns {void}
     */
    const addMessage = (role) => { if (role === 'system') return; form.messages.push({ role, content: '' }); emitSave() }

    /**
     * 删除消息
     * @param {number} index 索引
     * @param {string} role 角色
     * @returns {void}
     */
    /**
     * 删除用户消息（保留第一个）
     * @param {number} index 用户消息局部索引
     * @returns {void}
     */
    const removeUserMessage = (index) => {
      const indices = form.messages.map((m, i) => (m.role === 'user' ? i : -1)).filter(i => i >= 0)
      if (indices.length <= 1 || index === 0) return
      const globalIndex = indices[index]
      if (typeof globalIndex === 'number') {
        form.messages.splice(globalIndex, 1)
        emitSave()
      }
    }

    /**
     * 关闭抽屉保存名称
     * @returns {void}
     */
    const onClose = () => {
      const name = (form.name || '').toString().slice(0, 10)
      if (name) {
        emit('save', { name })
      }
      emit('close')
    }

    const nodeIconUnicode = computed(() => componentRegistry.getNodeConfig('llm')?.iconUnicode || '')
    const nodeIconColor = computed(() => {
      const cfg = componentRegistry.getNodeConfig('llm')
      return props.nodeData?.color || cfg?.color || '#333333'
    })

    const systemMessages = computed(() => form.messages.filter(m => m.role === 'system'))
    const userMessages = computed(() => form.messages.filter(m => m.role === 'user'))

    watch(() => props.nodeData, () => { initForm(); normalizeSystem(); ensureMinUserMessage() }, { immediate: true })
    watch(() => form.messages, () => { normalizeSystem(); ensureMinUserMessage() }, { deep: true })
    watch(() => form, () => emitSave(), { deep: true })

    return {
      form,
      modelOptions,
      systemMessages,
      userMessages,
      addContext,
      removeContext,
      addMessage,
      removeUserMessage,
      emitSave,
      onClose,
      nodeIconUnicode,
      nodeIconColor
    }
  }
})
</script>

<style scoped>
.drawer-header { display: flex; align-items: center; gap: 8px; }
.node-icon { font-family: iconfont; font-size: 20px; line-height: 1; }
.title { font-size: 16px; font-weight: 600; }
.drawer-body { padding: 8px 4px 16px 4px; }
.name-form :deep(.el-form-item__label) { width: auto !important; text-align: left; padding-right: 8px; }
.section { margin-top: 12px; }
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.model-select { width: 260px; }
.kv-list { display: flex; flex-direction: column; gap: 8px; }
.kv-row { display: grid; gap: 8px; align-items: center; }
.kv-row--context { grid-template-columns: 1fr 1fr 44px; }
.del-btn { padding: 2px; height: 24px; }
.del-btn :deep(.el-icon) { font-size: 14px; }
.msg-list { display: flex; flex-direction: column; gap: 8px; }
.msg-item { display: flex; flex-direction: column; gap: 8px; }
/* msg-tools 已移除 */
.adv-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; align-items: center; }
.adv-item { display: flex; align-items: center; gap: 8px; }
.adv-label { color: #666; width: 90px; text-align: left; }
</style>
.msg-actions { display: flex; justify-content: flex-end; }
